package leetCode;

import java.util.ArrayList;
import java.util.List;

public class WordSubsets {
    public List<String> wordSubsets(String[] A, String[] B) {

        int[] req=new int[26];
        for (String b :
                B) {
            int[] freq=getFreq(b);
            for (int i = 0; i < freq.length; i++) {
                req[i]=Math.max(req[i],freq[i]);
            }
        }
        List<String> res=new ArrayList<>();
        for (String a :
                A) {
            if(satifsfy(a,req)){
                res.add(a);
            }
        }
        return res;
    }

    private boolean satifsfy(String a, int[] req) {
        int[] freq=getFreq(a);
        for (int i = 0; i < freq.length; i++) {
            if(freq[i]<req[i]){
                return false;
            }
        }
        return true;
    }

    private int[] getFreq(String b) {
        int[] res=new int[26];
        for (int i = 0; i < b.length(); i++) {
            int ch=b.charAt(i)-'a';
            res[ch]++;
        }
        return res;
    }
}
